<?php

namespace app\modules\setting\controllers\cpgl;

use app\common\helper\CommonHelper;
use Yii;
use app\modules\setting\models\cpgl\QlUserTiktokProductGoods;
use app\modules\setting\configs\cpgl\CplbConfig;
use app\modules\setting\models\cpgl\QlUserTiktokProductGoodsSearch;
use sookie\react\AdminController;
use yii\helpers\ArrayHelper;
use yii\helpers\Json;
use yii\base\Exception;
use sookie\excel\SaveExcel;
use sookie\db\DBHandler;


/**
 * CplbController implements the CRUD actions for QlUserTiktokProductGoods model.
 */
class CplbController extends AdminController
{
    /**
    * @return array
    * 列表数据
    */
    public function actionIndex()
    {
        try {
            $searchModel = new QlUserTiktokProductGoodsSearch();
            $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
            $data = $dataProvider->getModels();
            if($data){
                $data = array_map(function($item){
                    $re = $item;
                    if(is_object($item)){
                        $re = $item->toArray();
                    }
                    $re['name'] = CommonHelper::getProductName($item);
                    return $re;
                },$data);
            }
            return ArrayHelper::merge(["data" =>$data, "pagination" => $dataProvider->getPagination()],CplbConfig::configIndex());
        }catch (\Throwable $e){
            return ["ok" => false,"msg" => $e->getMessage(),"code" => 401];
        }
    }






    protected function findModel($id)
    {
        if (($model = QlUserTiktokProductGoods::findOne($id)) !== null) {
            return $model;
        }

        throw new Exception('不存在的记录');
    }



    /**
    * @throws \PhpOffice\PhpSpreadsheet\Exception
    * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
    * 导出
    */
    public function actionExport(){
        try {
            $tableConfig = CplbConfig::getExcelHeaderMap();
            $searchModel = new QlUserTiktokProductGoodsSearch();
            $params = ArrayHelper::merge(Yii::$app->request->get(),["pageSize" => 0,"page" => 1]);
            $dataProvider = $searchModel->search($params,array_values($tableConfig["config"]));
            $dataArr = ArrayHelper::toArray($dataProvider->getModels());
        
            if (!$dataArr){
            throw new Exception("没有可导出的数据");
            }
            $handler = new SaveExcel([
            'fileName' => $tableConfig["fileName"],
            'format' => $tableConfig["format"],
            "array" => $dataArr,
            'headerDataArray' => array_keys($tableConfig["config"]),
            ]);
        
            $handler->arrayToExcel();exit;
        }catch (\Throwable $e){
            return ["ok" => false,"msg" => $e->getMessage(),"code" => 401];
        }
    }

}

